<template>
  <div>
    <el-card class="header">
      <el-steps
        :active="3"
        align-center
      >
        <el-step title="企业发起签约" />
        <el-step title="个人签署电子协议" />
        <el-step title="签约成功" />
      </el-steps>
      <el-alert
        type="success"
        :closable="false"
      >
        <template v-slot="title">
          <p>温馨提示:</p>
          <p>
            1.请准确填写真实用工信息，平台会进行身份校验，校验成功方能发起签约。
          </p>
          <p>
            2.单次导入上限500条，签约信息提交后，个人将收到短信提醒签约。
          </p>
        </template>
      </el-alert>
      <div class="form">
        <el-form
          ref="employmentContractFormRef"
          :model="employmentContractForm"
          :rules="rules"
          label-width="auto"
        >
          <el-form-item
            label="签约业务类型:"
            prop="busType"
          >
            <el-select
              v-model="employmentContractForm.busType"
              placeholder="请选择"
              @change="busTypeChange"
              style="width: 240px"
            >
              <el-option
                v-for="(item,i) in busTypeList"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="签约企业:"
            v-if="isSelecMer"
            prop="merId"
          >
            <el-select
              v-model="employmentContractForm.merId"
              placeholder="请选择"
              @change="merChange"
              style="width: 240px"
            >
              <el-option
                v-for="(item,i) in merList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              />
            </el-select>
          </el-form-item>


          <el-form-item label="签约文件导入:">
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              :action="uploadFileUrl"
              :headers="headers"
              :data="uploadFileData"
              :limit="1"
              :show-file-list="false"
              ref="uploadRef"
              :before-upload="beforeUpload"
              :on-success="uploadSuccess"
              :on-error="uploadError"
            >
              <el-button
                type="primary"
                icon="Upload"
              >导入发起用工签约</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
         <!-- v-hasRoles="['merchant']" -->
        <el-button
          class="import_btn"
          link
          type="primary"
          @click="employmentContractDownloadFun"
        >签约导入模板.XLSX</el-button>
      </div>
    </el-card>
    <!-- 上传loading -->
    <el-dialog
      v-model="loadingDialog"
      title="温馨提示"
      width="800px"
      :close-on-click-modal="false"
    >
      <div style="display: flex;justify-content: center;">
        <div>
          <p>1.请仔细检查导入文件的数据格式，身份证尾数含X的请替换成大写;</p>
          <p>2.上传文件数据上限500条，超出上限的请分次导入;</p>
          <p>3.为保证个人资金安全，平台将校验已导入的个人信息是否真实;</p>
          <p>4.单次导入数据超50条的，数据校验时间预计2~3分钟.</p>
          <div style="text-align: center;color: #1890ff;font-size: 17px;margin-top: 40px;">
            数据校验中，请耐心等待。。。
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="loadingDialog = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      title="导入结果"
      v-model="resultDialog"
      width="800px"
      :close-on-click-modal="false"
    >
      <div style="display: flex;justify-content: center;text-align: center;">
        <div>
          <img src="@/assets/images/success.png" style="width:50px;height:50px;" />
          <div style="text-align: center;color: #1890ff;font-size: 17px;margin-top: 10px;letter-spacing: 2px;">
            总共<span style="color:black;font-weight:700;font-size:20px;">{{resultData.cnt}}</span>条,导入成功<span style="color:green;font-weight:700;font-size:20px;">{{resultData.successCnt}}</span>条,失败<span style="color:red;font-weight:700;font-size:20px;">{{resultData.failCnt}}</span>条
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resultDialog = false">关 闭</el-button>
          <el-button @click="downError(resultData.downId)" v-if="resultData.downId">下载签约失败信息</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="employmentContract" lang="ts">
import api from '@/api/workMag/contractInquiry';
import { EmploymentContractForm } from '@/api/workMag/contractInquiry/types';
import { globalHeaders } from '@/utils/request';
import useUserStore from '@/store/modules/user';
import { UploadFiles, UploadRawFile } from 'element-plus';
const emit = defineEmits(['getList'])
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wxfe_bus_type } = toRefs<any>(proxy?.useDict('wxfe_bus_type'));
const resultDialog = ref(false);
const employmentContractForm = ref<EmploymentContractForm>({
  merId:'',
  sydId: '' ,
  busType: ''
});
const busTypeList = ref<DictDataOption[]>([]);
const employmentContractFormRef = ref();
const selBtByMsFun = async () => {
  const res = await api.selBtByMs(employmentContractForm.value);
  if (res.data && res.data.length) {
    wxfe_bus_type.value.forEach((e: DictDataOption) => {
      res.data.forEach((el: any) => {
        if (e.value == el) {
          busTypeList.value.push(e);
        }
      });
    });
  }
};

const selServiceBusType = async () => {
  const res = await api.selBusType();
  if (res.data && res.data.length) {
    wxfe_bus_type.value.forEach((e: DictDataOption) => {
      res.data.forEach((el: any) => {
        if (e.value == el) {
          busTypeList.value.push(e);
        }
      });
    });
  }
};


  const rules = reactive({
    busType: [
      {
        required: true,
        message: "签约业务类型不能为空",
        trigger: 'change'
      }
    ]
  })

const busTypeChange = async (e: any) => {
  uploadFileData.value.busType = e;
};

const merChange = (e: any) => {
  uploadFileData.value.merId = e;
  merList.value.some(item=>{
      if(item.id == e){
        uploadFileData.value.merNo = item.no;
        return true;
      }
  })
};

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(baseUrl + '/payment/workerBusiness/upload'); // 上传文件服务器地址
const headers = ref(globalHeaders());
const uploadFileData = ref<any>({
  busType: '',
  sydId: useUserStore().defaultProvider.sydId ,
  sydNo: useUserStore().defaultProvider.sydNo,
  domain: window.location.origin,
  merId: useUserStore().defaultProvider.merId,
  merNo: useUserStore().defaultProvider.merNo
});
const fileList = ref<UploadFile[]>([]);




const employmentContractDownloadFun = async () => {
  proxy?.download('/resource/oss/download/100', {}, `签约导入模板.xlsx`);
};

const downError = (id)=>{
  proxy?.download('/payment/workerBusiness/exportError', {
    uuid:id
  }, `签约导入模板.xlsx`);
}

const uploadRef = ref<ElUploadInstance>();
const loadingDialog = ref<boolean>(false);
const fileType = ref(["xlsx"]);
const fileSize = ref(5);
const beforeUpload = async (file: UploadRawFile) => {
  const data = await  employmentContractFormRef.value?.validate();
  if(!data){
    return false;
  }

  // 校检文件类型
  if (fileType.value.length) {
      const fileName = file.name.split('.');
      const fileExt = fileName[fileName.length - 1];
      const isTypeOk = fileType.value.indexOf(fileExt) >= 0;
      if (!isTypeOk) {
          proxy?.$modal.msgError(`文件格式不正确, 请上传${fileType.value.join("/")}格式文件!`);
          return false;
      }
  }
  // 校检文件大小
  if (fileSize.value) {
      const isLt = file.size / 1024 / 1024 < fileSize.value;
      if (!isLt) {
          proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize.value} MB!`);
          return false;
      }
  }
   loadingDialog.value = true;



   return true;
};
const resultData = ref({
  cnt:0,
  successCnt:0,
  failCnt:0,
  downId:''
})
const uploadSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log(response);
  loadingDialog.value = false;
  uploadRef.value?.clearFiles();
  if(response.code == 200){
    emit('getList',{});
    resultData.value = response.data;
    resultDialog.value = true;
  }else{
    proxy?.$modal.msgError(response.msg);
  }
};
const uploadError = (error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  uploadRef.value?.clearFiles();
  loadingDialog.value = false;
};

const isSelecMer = ref(false);
const merList = ref([])
onMounted(() => {
  let curRoleId = useUserStore().curRoleId;
  if(curRoleId == 9){
    isSelecMer.value = false;
    uploadFileData.value.sydId = useUserStore().defaultProvider.sydId;
    uploadFileData.value.sydNo = useUserStore().defaultProvider.sydNo;
    uploadFileData.value.merId = useUserStore().defaultProvider.merId;
    uploadFileData.value.merNo = useUserStore().defaultProvider.merNo;
    employmentContractForm.value.merId = useUserStore().defaultProvider.merId;
    employmentContractForm.value.sydId = useUserStore().defaultProvider.sydId;

    setTimeout(() => {
        selBtByMsFun();
      }, 500);
  }else if(curRoleId == 6){
    isSelecMer.value = true;

    rules.merId =  [
        {
          required: true,
          message: "签约企业不能为空",
          trigger: 'change'
        }
      ];
    uploadFileData.value.sydId = useUserStore().userInfo.busId;
    uploadFileData.value.sydNo = useUserStore().userInfo.busNo;
    api.listMer().then(res=>{
      if(res.data){
        merList.value = res.data;
      }
    });
    setTimeout(() => {
        selServiceBusType();
    }, 500);
  }

});
</script>

<style lang="scss" scoped>
.header {
  padding: 20px 0;
  .el-steps {
    margin-bottom: 30px;
  }
  .el-alert {
    margin-bottom: 30px;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    p {
      font-size: 14px;
      line-height: 24px;
      color: rgba(0, 0, 0, 0.65);
      margin: 0;
    }
  }
  .form {
    display: flex;
    flex-direction: column;
    align-items: center;

    .import_btn {
      margin-top: 10px;
    }
  }
}
</style>
